﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ADHelper.cs" company="Collaboris Ltd.">
//   Copyright (c) Collaboris Ltd. All rights Reserved.
// </copyright>
// <summary>
//   Defines the ADHelper type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Collaboris.Utils
{
    using System;
    using System.DirectoryServices;

    public class ADHelper
    {
        /// <summary>
        /// Creates the user account.
        /// </summary>
        /// <param name="login">The login.</param>
        /// <param name="password">The password.</param>
        /// <param name="fullName">The full name.</param>
        /// <param name="isAdmin">if set to <c>true</c> [is admin].</param>
        public static void CreateUserAccount(string login, string password, string fullName, bool isAdmin)
        {
            DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
            DirectoryEntries entries = dirEntry.Children;
            DirectoryEntry newUser = entries.Add(login, "user");
            
            newUser.Properties["FullName"].Add(fullName);
            newUser.Invoke("SetPassword", password);
            newUser.CommitChanges();

            DirectoryEntry grp;
            if (isAdmin)
            {
                grp = dirEntry.Children.Find("Administrators", "group");
                if (grp != null)
                {
                    grp.Invoke("Add", new object[] { newUser.Path.ToString() });
                }
            }
            else
            {
                grp = dirEntry.Children.Find("Guests", "group");
                if (grp != null)
                {
                    grp.Invoke("Add", new object[] { newUser.Path.ToString() });
                }
            }
        }

        /// <summary>
        /// Deletes the user account.
        /// </summary>
        /// <param name="login">The login.</param>
        public static void DeleteUserAccount(string login)
        {
            try
            {
                DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
                DirectoryEntry user = dirEntry.Children.Find(login, "User");

                if (user != null)
                {
                    dirEntry.Children.Remove(user);
                }

                dirEntry.Close();
            }
            catch (Exception exception) {}
        }

    }
}
